import React , { Component } from 'react';
import TodoItem from './TodoItem.js';
import './Todo.css';
import PropTypes from 'prop-types';
import store from "./Store";

class TodoList extends Component{
    constructor(props, context){
        super(props, context);
        this.getOwnState = this.getOwnState.bind(this);
        this.onChange = this.onChange.bind(this);
        this.state=this.getOwnState();
    };

    getOwnState(){
        console.log(this.context.store.getState());
        return {
            items: this.context.store.getState()
        }
    };

    onChange() {
        this.setState(this.getOwnState());
    };

    componentDidMount() {
        this.context.store.subscribe(this.onChange);
    }

    componentWillUnmount() {
        this.context.store.unsubscribe(this.onChange);
    }


    render(){
        const items = this.state.items;
        return(
            <div className="todo-list">
                {
                    (items.length !==0)?(items.map((item) =>{
                        if(item.complete === true){
                            return <TodoItem key={item.id} item={item} class='complete' />
                        }
                        return <TodoItem key={item.id} item={item} class="uncomplete" />
                    })):<div className="no-list">您的事项列表空空如也</div>
                }
            </div>
        )

    }
}

TodoList.contextTypes = {
    store: PropTypes.object
};


export default TodoList;